package com.shanks.home.module.multythread;

import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.ImageView;

import com.shanks.home.R;

/**
 * @author Shanks
 * @time 2013.11.20
 */
public class ShanksHandlerActivity extends Activity {
	
	private ImageView photoIV;
	private int[] photoIds;
	private int currentPhotoId;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		this.setContentView(R.layout.activity_shankshandler);
		initView();
		testHandler();
	}
	
	private void initView() {
		photoIV = (ImageView)this.findViewById(R.id.shankshandler_photo_iv);
	}
	
	private void testHandler() {
		photoIds = new int[]{
				R.drawable.imgface_1,
				R.drawable.imgface_2,
				R.drawable.imgface_3,
				R.drawable.imgface_4,
				R.drawable.imgface_5
		};		
		
		currentPhotoId = 0;
		
		final Handler handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				
				if (msg.what == 0x1125) {
					if (currentPhotoId >= 5) {
						currentPhotoId = 0;
					}
					photoIV.setImageResource(photoIds[currentPhotoId ++]);
				}
			}
		};
		
		// 定义一个定时器，周期性地执行指定的任务
		new Timer().schedule(new TimerTask() {
			
			@Override
			public void run() {
				// 新启动的线程无法访问该Activity里的组件，所以需要通过handler发送消息
				Message message = new Message();
				message.what = 0x1125;
				handler.sendMessage(message);
			}
		}, 0, 1000);
	}
}